const express = require('express')
const Router = express.Router()
const query = require('./db')
// 导入加密模块，是内置模块，不需要下载
const crypto = require('crypto');
const jwt = require('jsonwebtoken');

//token密钥
let secret = 'doublefly'

module.exports = Router

/**
 * p判断当前用户名是否已经存在
 */
Router.post('/existUsername', async (req, res) => {
    try {
        let { username } = req.body
        let data = await query(`select * from user where user_name='${username}'`)
        if (data.length === 0) {
            res.send({
                code: 200,
                msg: '当前用户名可注册',
                data
            })
            return
        }
        res.send({
            code: 400,
            msg: '当前用户名已存在',
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

/**
 * 注册接口
 */
Router.post('/registerUser', async (req, res) => {
    try {
        let { username, password, email } = req.body
        // 创建加密方式 为md5加密方式
        let md5 = crypto.createHash('md5')
        // 用md5把密码更新加密
        md5.update(password);
        // 签名认证之后把密码以hex的编码方式导出
        let mdPassword = md5.digest('hex');
        await query(`insert into user values(${null},'${username}','${mdPassword}','${email}','还没有地址','1',${null},'${process.env.BASE_URL}/images/avatar/default_avatar.png',${null},'这个用户很懒，还没有说明','保密')`)
        res.send({
            code: 200,
            msg: '注册成功',
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

/**
 * 登录接口
 */
Router.post('/login', async (req, res) => {
    try {
        let { username, password } = req.body
        let md5 = crypto.createHash('md5')
        md5.update(password)
        let mdPassword = md5.digest('hex')
        let data = await query(`select * from user where user_name='${username}' and user_password='${mdPassword}';`)
        await query(`update user set user_online='1' where user_id=${data[0].user_id}`)
        if (data.length === 0) {
            res.send({
                code: 400,
                msg: '用户名或密码错误'
            })
            return
        }
        if (data[0].user_type !== '1') {
            res.send({
                code: 400,
                msg: '该账号已经被冻结'
            })
            return
        }
        let info = {
            ...data[0]
        }
        let userInfo = { ...info }
        delete userInfo.user_password

        // 登录成功 生成token令牌
        // jwt.sign()
        // 三个参数：参数1：payload 用户相关信息，参数2：秘钥，参数3：一个对象，过期时间，创建token的时间，或者token的id值
        let token = jwt.sign(info, secret, {
            //Token有效时间 单位s
            expiresIn: 60 * 60 * 10,
        })
        res.send({
            code: 200,
            msg: '登录成功',
            token,
            userInfo
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

/**
 * 退出登录接口
 */
Router.get('/logout', async (req, res) => {
    try {
        let { user_id } = req.query
        let data = await query(`update user set user_online='0' where user_id=${user_id}`)
        if (data) {
            res.send({
                code: 200,
                msg: '退出登录成功',
                data
            })
        }

    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})
